﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.ModelBinding;
using Altairis.FluffyCloud.Data;
using Altairis.Web;

namespace Altairis.FluffyCloud.WebCore.Pages.Forum {

    public partial class Settings : System.Web.UI.Page {

        public IEnumerable<object> CategoryList_GetData() {
            using (var dc = new FluffyDbContext()) {
                var categories = dc.TopicCategories.AsQueryable();
                if (!System.Web.Security.Roles.IsUserInRole(Role.AdministratorsRoleName)) categories = categories.Where(x => !x.IsSystemCategory);
                var q = from c in categories
                        orderby c.Name
                        select new {
                            Text = c.Name + (c.IsSystemCategory ? " (systémová)" : ""),
                            Value = c.TopicCategoryId
                        };
                return q.ToArray();
            }
        }

        public Topic FormView_GetItem([RouteData("id")]int topicId) {
            using (var dc = new FluffyDbContext()) {
                var t = dc.Topics.SingleOrDefault(x => x.TopicId == topicId);
                if (System.Web.Security.Roles.IsUserInRole(Role.AdministratorsRoleName) || t.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) {
                    // Owner or admin
                    this.LiteralCurrentCategory.Text = string.Format(this.LiteralCurrentCategory.Text, t.TopicCategory.Name);
                    return t;
                }
                else {
                    // Neither owner or admin
                    this.Response.SendErrorResponse(401, "Unauthorized", "You must be forum owner od administrator");
                    return null;
                }
            }
        }

        public void FormView_UpdateItem([RouteData("id")]int topicId) {
            using (var dc = new FluffyDbContext()) {
                // Read item and load changes
                var topic = dc.Topics.SingleOrDefault(x => x.TopicId == topicId);
                TryUpdateModel(topic);
                if (!ModelState.IsValid) return;

                // Verify rights
                if (!System.Web.Security.Roles.IsUserInRole(Role.AdministratorsRoleName) && !topic.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) {
                    this.ModelState.AddModelError("AccessDenied", "Nemáte právo měnit toto fórum");
                }

                // Verify name is unique
                topic.Name = topic.Name.Trim();
                if (dc.Topics.Any(x => x.Name.Equals(topic.Name, StringComparison.CurrentCultureIgnoreCase) && x.TopicId != topic.TopicId)) {
                    this.ModelState.AddModelError("ForumAlreadyExists", "Fórum s tímto nebo podobným názvem již existuje");
                }

                // Save changes
                if (!ModelState.IsValid) return;
                try {
                    dc.SaveChanges();
                    this.Response.RedirectToRoute("ForumDetail");
                }
                catch (Exception ex) {
                    this.ModelState.AddModelError("SaveError", ex);
                }
            }
        }

        protected void ButtonDelete_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            var topicId = int.Parse(this.RouteData.Values["id"] as string);

            using (var dc = new FluffyDbContext()) {
                // Read item
                var topic = dc.Topics.SingleOrDefault(x => x.TopicId == topicId);

                // Verify rights
                if (!System.Web.Security.Roles.IsUserInRole(Role.AdministratorsRoleName) && !topic.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) {
                    this.ModelState.AddModelError("AccessDenied", "Nemáte právo měnit toto fórum");
                }

                // Delete forum
                dc.Topics.Remove(topic);

                // Save changes
                if (!ModelState.IsValid) return;
                try {
                    dc.SaveChanges();
                    this.Response.RedirectToRoute("HomePage");
                }
                catch (Exception ex) {
                    this.ModelState.AddModelError("SaveError", ex);
                }
            }
        }

        protected void ButtonSetCategory_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            var topicId = int.Parse(this.RouteData.Values["id"] as string);
            var newCategoryId = int.Parse(this.CategoryList.SelectedValue);

            using (var dc = new FluffyDbContext()) {
                // Read item
                var topic = dc.Topics.SingleOrDefault(x => x.TopicId == topicId);

                // Verify rights
                if (!System.Web.Security.Roles.IsUserInRole(Role.AdministratorsRoleName) && !topic.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) {
                    this.ModelState.AddModelError("AccessDenied", "Nemáte právo měnit toto fórum");
                }

                // Change category
                topic.TopicCategoryId = newCategoryId;

                // Save changes
                if (!ModelState.IsValid) return;
                try {
                    dc.SaveChanges();
                    this.Response.RedirectToRoute("ForumDetail");
                }
                catch (Exception ex) {
                    this.ModelState.AddModelError("SaveError", ex);
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e) {
        }
    }
}